﻿// LocalStorageService.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.Json;

public static class LocalStorage
{
    private static readonly string StoragePath =
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
        "上位机程序/storage.json");

    private static Dictionary<string, string> _storage;

    static LocalStorage()
    {
        Load();
    }

    /// <summary>
    /// 保存键值对（自动持久化到文件）
    /// </summary>
    public static void Set(string key, string value)
    {
        _storage[key] = value;
        Save();
    }

    /// <summary>
    /// 获取值（键不存在时返回null）
    /// </summary>
    public static string Get(string key)
    {
        return _storage.TryGetValue(key, out var value) ? value : null;
    }

    /// <summary>
    /// 删除键值对
    /// </summary>
    public static void Remove(string key)
    {
        if (_storage.Remove(key))
        {
            Save();
        }
    }

    /// <summary>
    /// 清空所有存储
    /// </summary>
    public static void Clear()
    {
        _storage.Clear();
        Save();
    }

    private static void Load()
    {
        try
        {
            if (File.Exists(StoragePath))
            {
                var json = File.ReadAllText(StoragePath);
                _storage = JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new();
            }
            else
            {
                _storage = new();
            }
        }
        catch
        {
            _storage = new();
        }
    }

    private static void Save()
    {
        try
        {
            Directory.CreateDirectory(Path.GetDirectoryName(StoragePath));
            var json = JsonSerializer.Serialize(_storage);
            File.WriteAllText(StoragePath, json);
        }
        catch (Exception ex){ /* 处理写入失败 */
            Debug.WriteLine("LocalStorage Write File Error:  " + ex.Message);
        }
    }
}